<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="5" :lg="7" :md="8" :sm="24">
            <a-form-item label="区域">
              <j-select-depart
                placeholder="请选择区域"
                v-model="queryParam.areaId"
                @selectDepart="handleSelectDepart"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="7" :md="8" :sm="24">
            <a-form-item label="农污终端">
              <a-select
                v-model="queryParam.terminalId"
                show-search
                allowClear
                placeholder="请选择"
                :default-active-first-option="false"
                :show-arrow="false"
                :not-found-content="null"
                option-filter-prop="children"
              >
                <!-- 显示终端名称+编号 -->
                <a-select-option :value="undefined">请选择</a-select-option>
                <a-select-option v-for="item in terminalList" :key="item.value" :value="item.value">
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="7" :md="8" :sm="24">
            <a-form-item label="设备类型">
              <a-select style="width: 220px" v-model="queryParam.equType" placeholder="请选择">
                <a-select-option value="">全部</a-select-option>
                <a-select-option v-for="(item, i) in equTypeList" :key="i" :value="item.value">{{
                  item.label
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="7" :md="8" :sm="24">
            <a-form-item label="设备名称">
              <a-input v-model="queryParam.equName" change="changEquName" placeholder="请输入设备名称" allowClear />
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="7" :md="8" :sm="24">
            <a-form-item label="进出水口">
              <a-select style="width: 220px" v-model="queryParam.impExp" placeholder="请选择">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="1">进水口</a-select-option>
                <a-select-option value="2">出水口</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">设备列表</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <!-- 操作按钮区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="时间段">
              <a-range-picker
                v-model="date"
                :ranges="ranges"
                @change="onChange"
                format="YYYY-MM-DD"
                valueFormat="YYYY-MM-DD"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-button type="primary" @click="searchEquData" style="margin-left: 8px"> 数据查询 </a-button>
            <a-button @click="exportListToPDF" type="primary" style="margin-left: 8px">导出</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 内容-begin -->
    <div class="conetnt-wrap">
      <div
        class="equ-list-wrap"
        v-infinite-scroll="loadMore"
        :infinite-scroll-immediate-check="false"
        infinite-scroll-disabled="busy"
        infinite-scroll-distance="10"
        infinite-scroll-throttle-delay="1000"
      >
        <div v-if="total === null" class="default-tip">
          请选择最底层区划<br />
          获取查看设备
        </div>
        <div v-else-if="total === 0" class="default-tip">该区划暂无设备</div>
        <template v-else>
          <div v-for="(item, j) in equList" :key="item.id">
            <a-checkbox :checked="item.checked" @change="onChangeSlectEqu(item, j)">
              <div class="equ-name" :title="`${item.equName}(${item.equNo})`">{{ item.equName }}({{ item.equNo }})</div>
            </a-checkbox>
          </div>
        </template>
      </div>
      <div class="equdata-echart" id="equdata-echart">
        <div :id="id" style="width: 100%; height: 100%"></div>
      </div>
    </div>
    <!-- 内容-end -->
  </a-card>
</template>

<script>
import { getDictItemListByCode } from '@/api/system.js'
import { getAreaEquList, getpipCurve, getpipEquipTrCurve } from '@/api/dataQuery.js'
import { filterObj } from '@/utils/util'
import { httpAction, getAction } from '@/api/manage'
import * as echarts from 'echarts'
import moment from 'moment'
import html2canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default {
  name: 'PaishuiDataQuery',
  data() {
    return {
      loading: false,
      queryParam: {
        areaId: '1638530805038878721', //'',
        terminalId: '',
        impExp: '',
        equType: '1',
        equName: '',
      },
      equTypeList: [],
      date: [],
      ranges: {
        当天: [moment().startOf('day'), moment().endOf('day')],
        一周: [moment().startOf('day').subtract(7, 'days'), moment().endOf('day')],
        十五天: [moment().startOf('day').subtract(15, 'days'), moment().endOf('day')],
      },
      equList: [],
      total: null,
      pageNo: 0,
      pageSize: 20,
      busy: false,
      selectEquIds: [],
      selectEquName: [],
      equData: [],
      id: '',
      myChart: null,
      range: [0.4, 1],
      color: '21,71,163',
      colorList: ['rgba(21,71,163, 1)'],
      terminalList: [], // 农污终端列表
    }
  },
  computed: {
    eChartTitle() {
      const equType = this.queryParam.equType
      if (equType === 1) {
        return '液位高度折线图'
      } else {
        return '数据查询图表'
      }
    },
  },
  created() {
    this.getTerminalList()
    this.init()
    this.handleGetDictItemList('ps_equ_type')
  },
  beforeDestory() {
    this.disposeCharts()
  },
  methods: {
    async getTerminalList() {
      try {
        const res = await getAction(`/terminal/terminal/list`, { pageNo: 1, pageSize: 10000 })
        const terminalList = res.result.records || []
        this.terminalList = terminalList.map((terminal) => ({
          value: terminal.terminalId,
          label: `${terminal.terminalName}(${terminal.terminalId})`,
        }))
      } catch (error) {
        console.log(error)
      }
    },
    changEquName(equName) {
      this.queryParam.equName = equName ? equName.replace(/(^\s*)|(\s*$)/g, '') : ''
    },
    loadMore: function () {
      const { total } = this
        if ( total &&total <= this.equList.length||total==0) {
          this.busy = true
          return
        }
        this.busy = true
        this.pageNo++
        this.handleGetAreaEquList()
    },
    init() {
      this.id = Math.ceil(Math.random() * 10000)
    },
    buildColorList() {
      let result = this.colorList
      const item = (this.range[1] - this.range[0]) / (this.data || [{}]).length
      result = (this.data || []).map((x, index) => {
        return 'rgba(' + this.color + ', ' + (((this.range || [])[0] || 0) - -(item * (index - -1))) + ')'
      })
      this.colorList = result
    },
    async handleGetDictItemList(dictCode) {
      const res = await getDictItemListByCode({ dictCode })
      this.equTypeList = (res.result || []).map((x) => {
        return {
          name: x.itemText,
          label: x.itemText,
          value: x.itemValue,
        }
      })
    },
    async handleGetAreaEquList(page) {
      if (page === 1) {
        this.pageNo = 1
      }
      const { queryParam, pageNo, pageSize } = this
      const param = filterObj({ ...queryParam, pageNo: page ? page : pageNo, pageSize })
      const res = await getAreaEquList(param)
      this.busy = false
      if (res.success) {
        const equList = res.result.records || res.result
        this.selectEquIds = []
        this.myChart = null
        if (pageNo === 1) {
          this.equList = equList.map((item) => {
            item.checked = false
            return item
          })
        } else {
          this.equList = [
            ...this.equList,
            ...equList.map((item) => {
              item.checked = false
              return item
            }),
          ]
        }
        this.total = res.result.total || 0
      } else {
        this.$message.warning(res.message)
      }
    },
    searchEquData() {
      console.log('searchEquData')
      if (!this.date.length) {
        this.$message.warn('请选择设备显示时间范围')
        return
      }
      const equType = this.queryParam.equType
      console.log('equType', equType)
      // ['液位计 1','流量计 2','氨氮 3','PH 4','COD 5','电导率 6','投入式液位计 7']
      // ['cm 液位高度','m3/h 流量','mg/L 氨氮含量','PH值 PH值','mg/L COD','us/cm 电导率','cm 液位高度']
      if (equType === '1') {
        this.showLiquidHeightEchart()
      } else if (equType === '2') {
        // 设备类型-流量计-曲线图
        this.showTrLiquidHeightEchart('m3/h', '流量')
      } else if (equType === '3') {
        // 设备类型-氨氮-曲线图
        this.showTrLiquidHeightEchart('mg/L', '氨氮含量')
      } else if (equType === '4') {
        // // 设备类型-PH值-曲线图
        this.showTrLiquidHeightEchart('PH值', 'PH值')
      } else if (equType === '5') {
        // 设备类型-COD-曲线图
        this.showTrLiquidHeightEchart('mg/L', 'COD')
      } else if (equType === '6') {
        // 设备类型-电导率-曲线图
        this.showTrLiquidHeightEchart('us/cm', '电导率')
      } else if (equType === '7') {
        // 设备类型-投入式液位计-曲线图
        this.showTrLiquidHeightEchart('cm', '液位高度')
      } else if (equType === '8') {
        // 设备类型-投入式液位计-曲线图
        this.showTrLiquidHeightEchart('A', '电流控制器')
      } else if (equType === '9') {
        // 设备类型-投入式液位计-曲线图
        this.showTrLiquidHeightEchart('--', '浊度')
      }
    },
    disposeCharts() {
      // 销毁echarts实例
      const myChart = this.myChart
      if (myChart) {
        this.myChart.dispose()
        this.myChart = null
      }
    },
    // generateColor() {
    //   let color = "";
    //   let r = Math.floor(Math.random() * 256);
    //   let g = Math.floor(Math.random() * 256);
    //   let b = Math.floor(Math.random() * 256);
    //   color = `rgb(${r},${g},${b})`;
    //   return color;
    // },
    // 展示液位高度折线图
    async showLiquidHeightEchart() {
      const [createdTimeSt, createdTimeEd] = this.date
      const selectEquIds = this.selectEquIds

      const resArr = await Promise.all(
        selectEquIds.map((equNo) => {
          const param = {
            createdTimeSt,
            createdTimeEd,
            equNo,
          }
          return getpipCurve(param)
        })
      )
      const dataArr = resArr.filter((res) => res.success).map((data) => data.result)
      const equitemList = this.equList.filter((equ) => selectEquIds.includes(equ.equNo))
      // console.log('equitemList', equitemList)
      // console.log('dataArr', dataArr)
      let formaterType = 1
      let splitNumber = 8
      let timeStart = new Date(createdTimeSt).getTime()
      let timeEnd = new Date(createdTimeEd).getTime()
      let timeRange = timeEnd - timeStart
      if (timeRange <= 24 * 3600 * 1000) {
        formaterType = 1
        splitNumber = 13
      } else if (timeRange <= 8 * 24 * 3600 * 1000) {
        formaterType = 2
        splitNumber = 6
      } else if (timeRange > 8 * 24 * 3600 * 1000) {
        formaterType = 3
        splitNumber = 18
      }
      // const legendArr = equitemList.map((item) => item.equName)
      const legendArr =this.selectEquName
      let yDataArrs = dataArr.map((yArr, i) => ({
        name: this.selectEquName[i],
        type: 'line',
        symbol: 'circle',
        showSymbol: true,
        // itemStyle:{
        //   normal:{
        //     color: this.generateColor()
        //   }
        // },
        data: yArr.map((data) => {
          return [data.reportTime, data.deviceData]
        }),
      }))
      console.log('yDataArrs', yDataArrs,legendArr)
      // 基于准备好的dom，初始化echarts实例
      this.disposeCharts()
      const chart = echarts.init(document.getElementById(this.id))
      let option = {
        title: {
          text: '液位高度折线图',
        },
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          data: legendArr,
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: [
          {
            type: 'time',
            boundaryGap: false,
            splitNumber,
            axisLabel: {
              formatter: function (value) {
                if (formaterType === 1) {
                  return new Date(value).format('hh:mm')
                } else if (formaterType === 2) {
                  return new Date(value).format('MM-dd')
                } else {
                  return new Date(value).format('dd')
                }
              },
            },
          },
        ],
        yAxis: [
          {
            type: 'value',
            name: 'cm',
          },
        ],
        series: yDataArrs,
      }
      chart.setOption(option)
      this.myChart = chart
    },
    // 展示投入也为u高度折线图
    async showTrLiquidHeightEchart(unit, chartTitle) {
      const [createdTimeSt, createdTimeEd] = this.date
      const selectEquIds = this.selectEquIds
      const resArr = await Promise.all(
        selectEquIds.map((equNo) => {
          const param = {
            createdTimeSt,
            createdTimeEd,
            equNo,
          }
          return getpipEquipTrCurve(param)
        })
      )
      const dataArr = resArr.filter((res) => res.success).map((data) => data.result)
      const equitemList = this.equList.filter((equ) => selectEquIds.includes(equ.equNo))
      // console.log('equitemList', equitemList)
      // console.log('dataArr', dataArr)
      let formaterType = 1
      let splitNumber = 8
      let timeStart = new Date(createdTimeSt).getTime()
      let timeEnd = new Date(createdTimeEd).getTime()
      let timeRange = timeEnd - timeStart
      if (timeRange <= 24 * 3600 * 1000) {
        formaterType = 1
        splitNumber = 13
      } else if (timeRange <= 8 * 24 * 3600 * 1000) {
        formaterType = 2
        splitNumber = 7
      } else if (timeRange > 8 * 24 * 3600 * 1000) {
        formaterType = 3
        splitNumber = 18
      }
      // const legendArr = equitemList.map((item) => item.equName)
    const legendArr =this.selectEquName
      let yDataArrs = dataArr.map((yArr, i) => ({
        name: equitemList[i].equName,
        type: 'line',
        symbol: 'circle',
        showSymbol: true,
        data: yArr.map((data) => {
          return [data.reportTime, data.deviceData]
        }),
      }))
      console.log('yDataArrs', yDataArrs)
      // 基于准备好的dom，初始化echarts实例
      this.disposeCharts()
      const chart = echarts.init(document.getElementById(this.id))
      let option = {
        title: {
          text: chartTitle + '折线图',
        },
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          data: legendArr,
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: [
          {
            type: 'time',
            boundaryGap: false,
            splitNumber,
            axisLabel: {
              formatter: function (value) {
                if (formaterType === 1) {
                  return new Date(value).format('hh:mm')
                } else if (formaterType === 2) {
                  return new Date(value).format('MM-dd')
                } else {
                  return new Date(value).format('dd')
                }
              },
            },
          },
        ],
        yAxis: [
          {
            type: 'value',
            name: unit,
          },
        ],
        series: yDataArrs,
      }
      chart.setOption(option)
      this.myChart = chart
    },
    onChangeSlectEqu(equ, j) {
      const checkedFlag = !equ.checked
      this.equList[j].checked = checkedFlag
      if (checkedFlag) {
        this.selectEquIds.push(equ.equNo)
        this.selectEquName.push(equ.equName)
        console.log(this.selectEquIds,'11.1999999999999999999')
      } else {
        this.selectEquIds = this.selectEquIds.filter((item) => item !== equ.equNo)
        this.selectEquName = this.selectEquName.filter((item) => item !== equ.equName)
        console.log(this.selectEquName,'11.1ddddddddddddddd')
      }
      if (this.date.length) {
        this.searchEquData()
      }
    },
    onChange(dates) {
      if (dates.length) {
        this.date = [dates[0] + ' 00:00:00', dates[1] + ' 23:59:59']
      } else {
        this.date = []
      }
    },
    handleSelectDepart(selectDepartArr) {
      const selectDepart = selectDepartArr[0]
      console.log(selectDepart, selectDepart.orgType)
      // if (selectDepart.orgType !== '6') {
      //   this.$message.warn('请选择最底层区划')
      //   return
      // }
    },
    searchQuery() {
      this.handleGetAreaEquList(1)
    },
    searchReset() {
      this.queryParam = {
        areaId: '',
        equType: '',
        impExp: '',
      }
      this.date = []
      this.handleGetAreaEquList(1)
    },
    async exportListToPDF() {
      if (!this.myChart) {
        this.$message.warning('暂无图表数据')
        return
      }
      this.exportData()
    },
    exportData() {
      const fileName = this.eChartTitle
      const el = document.getElementById('equdata-echart')
      html2canvas(el, {
        useCORS: true,
        allowTaint: true,
        scrollY: -window.scrollY,
      }).then((canvas) => {
        const image = canvas.toDataURL('image/jpeg', 1.0)
        const doc = new JsPDF('l', 'px', 'a4')
        const pageWidth = doc.internal.pageSize.getWidth()
        const pageHeight = doc.internal.pageSize.getHeight()

        const widthRatio = pageWidth / canvas.width
        const heightRatio = pageHeight / canvas.height
        const ratio = widthRatio > heightRatio ? heightRatio : widthRatio

        const canvasWidth = canvas.width * ratio
        const canvasHeight = canvas.height * ratio

        const marginX = (pageWidth - canvasWidth) / 2
        const marginY = (pageHeight - canvasHeight) / 2

        doc.addImage(image, 'JPEG', marginX, marginY, canvasWidth, canvasHeight)
        doc.save(`${fileName}.pdf`)
      })
    },
  },
}
</script>

<style scoped lang="less">
@import '~@assets/less/common.less';
.conetnt-wrap {
  display: flex;
  justify-content: flex-start;
  align-items: stretch;
  height: calc(100vh - 430px);
  margin-top: 40px;
}

.equ-list-wrap {
  width: 240px;
  min-width: 240px;
  overflow-y: auto;
}
.default-tip {
  padding: 20px;
  color: #999;
  text-align: center;
}
.equdata-echart {
  box-sizing: border-box;
  width: calc(100% - 200px);
  padding: 20px;
  border: 1px solid #999;
}

.equ-name {
  position: relative;
  top: 6px;
  white-space: nowrap;
  overflow: hidden;
  display: inline-block;
  width: calc(100% - 60px);
  text-overflow: ellipsis;
}

.ant-checkbox-wrapper {
  width: 100%;
}
</style>
